package face.pay.security.controller;

import face.pay.entity.UserInfo;
import face.pay.security.annotation.CurrentUser;
import face.pay.security.util.SecurityUserUtil;
import face.pay.util.ResultMessage;
import face.pay.web.user.service.IUserService;
import org.apache.catalina.security.SecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
public class SecurityController {

    Logger logger = LoggerFactory.getLogger(SecurityController.class);


    @RequestMapping("/index")
    public String index() {
         UserInfo userInfo =  SecurityUserUtil.getCurrentLoginUser();
         logger.info("用户："+userInfo.getUserName()+" 成功登陆");
         return "index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model,Boolean error,HttpServletRequest httpServletRequest) {

        if(new Boolean(true).equals(error)){
          UsernameNotFoundException exception =  (UsernameNotFoundException)httpServletRequest.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");

           if(exception!=null){
               String message = exception.getMessage();

               model.addAttribute("errorMessage",message);

           }
        }
        return "login";
    }





    @RequestMapping(value = "/timeOut")
    public  void sessionTimeOut(HttpServletRequest request, HttpServletResponse response) throws  Exception{

        System.out.println("超时");
        /**
         * 判断是否是ajax
         */
        if (request.getHeader("x-requested-with") != null
           && request.getHeader("x-requested-with").equalsIgnoreCase( "XMLHttpRequest")) {
            response.getWriter().print("{timeOut:true}");  //设置超时标识
            response.getWriter().close();
        }else {
            response.sendRedirect("/login");
        }

    }

}
